/**
 * Created by moc on 2016/3/29.
 */
var conf = require('../config.js').config

var mongo = require('mongoose')

var format = require('format')
    , printf = format.printf
    , vsprintf = format.vsprintf
// or if you want to keep it old school
    , sprintf = format

var config = {
    db: "mysql"
}


mongo.connect(conf.mongo.str);
var db = mongo.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function () {
    console.log("db opened")
});
//*************************************
var userSchema = mongo.Schema({
    username: {type: String, index: true},
    password: String
});
var User = mongo.model('user', userSchema)
//*************************************
var noteSchema = mongo.Schema({
    username: {type: String, index: true},
    content: String,
    title: String,
    time: {
        type: Date,
        default: Date.now
    }
});
var Note = mongo.model('note', noteSchema)
//Mongo
var UserMon = {}
var NoteMon = {}
UserMon.findOne = function (params, cb) {
    User.findOne(params, cb)
}
UserMon.find = function (params, cb) {
    User.find(params, cb)
}
UserMon.save = function (params, cb) {
    var user = new User(params)
    user.save(cb)
}
NoteMon.findOne = function (params, cb) {
    Note.findOne(params, cb)
}
NoteMon.find = function (params, cb) {
    Note.find(params, cb)
}
NoteMon.save = function (params, cb) {
    var note = new Note(params)
    note.save(cb)
}
//**************** MYSQL *********************
var mysql = require('mysql');
var connection = mysql.createConnection({
    host: '192.168.233.137',
    user: 'root',
    password: '999666',
    database: 'mynote'
});

var UserMy = {}
var NoteMy = {}
var arrayToSql = function (params) {

    var sql = ""
    var c = 0
    for (var k in params) {
        if (c == 0) {
            sql += " where "
        }
        var v = params[k]
        if (typeof v == "string") {
            v = '"' + v + '"'
        }
        var str = sprintf(" a.%s=%s ", k, v)
        if (c != 0) {
            str = " and " + str
        }
        sql = sql + str
        c += 1
    }
    return sql
}
var dbFind = function (db, params, cb) {
    var query = sprintf("select * from %s a ", db)
    query += arrayToSql(params)
    console.log(query)
    connection.query(query, function (err, rows, fields) {
        cb(err, rows)
        console.log(rows)
    });
}
var dbFindOne = function (db, params, cb) {
    var query = sprintf("select  * from %s a ", db)
    query += arrayToSql(params)
    query += " limit 0,1 "
    connection.query(query, function (err, rows, fields) {
        if (!err) {
            if (rows.length >= 1) {
                cb(err, rows[0])
            } else {
                cb(err, null)
            }
        } else {
            cb(err, null)
        }

    });
}
var dbSave = function (db, params, cb) {
    var query = sprintf("insert into %s ", db)
    var sql1 = ""
    var sql2 = ""
    var i = 0
    for (var k in params) {
        if (i != 0) {
            sql1 += " , "
            sql2 += " , "
        }
        var v = params[k]
        if (typeof  v == "string") {
            v = '"' + v + '"'
        }
        sql1 += sprintf(" %s ", k)
        sql2 += sprintf(" %s ", v)
        i += 1
    }
    query += sprintf(" ( %s ) values ( %s ) ", sql1, sql2)
    console.log(query)
    connection.query(query, function (err, rows, fields) {
        cb(err, rows)
    });
}
UserMy.find = dbFind.bind(null, "user")
UserMy.findOne = dbFindOne.bind(null, "user")
UserMy.save = dbSave.bind(null, "user")
NoteMy.find = dbFind.bind(null, "post")
NoteMy.findOne = dbFindOne.bind(null, "post")
NoteMy.save = dbSave.bind(null, "post")
connection.connect();
//

if (config.db == "mongodb") {
    exports.User = UserMon
    exports.Note = NoteMon
} else if (config.db == "mysql") {
    exports.User = UserMy
    exports.Note = NoteMy
}


//noteMy.findOne({id:1,username:"us"},function(err,data){console.log(data)})

//UserMy.save({username:"as",password:"kk"},function(err,data){console.log(data)})


